package com.weiaibenpao.demo.chislim.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;


import com.luck.picture.lib.permissions.RxPermissions;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.base.BaseActivity;
import com.weiaibenpao.demo.chislim.db.preferences.UserPreferences;
import com.weiaibenpao.demo.chislim.tts.util.SpeechUtil;
import com.weiaibenpao.demo.chislim.ui.activity.login.LoginActivity;
import com.weiaibenpao.demo.chislim.utils.Utils;

import io.reactivex.functions.Consumer;


public class SplashActivity extends BaseActivity {
    private Handler mHandler = new Handler();


    @Override
    public int setLayoutResourceID() {
        return R.layout.activity_splash;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        if (!isTaskRoot()) {
            Intent intent = getIntent();
            String action = intent.getAction();
            if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) {
                finish();
                return;
            }
        }
        if (checkCorePermissions()) {
            loading();
        }

        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if(aBoolean){
                    SpeechUtil.getInstance().init(getApplicationContext());
                }
            }
        });
    }

    private void loading() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (UserPreferences.getInstance().getBoolean(UserPreferences.IS_LOGGED_IN)) {
                    MainActivity.startSelf(SplashActivity.this);
                } else {
                    LoginActivity.startSelf(SplashActivity.this);
                }
                finish();
            }
        }, 2500);
    }


    private int REQUEST_FINE_LOCATION_CODE = 100;

    private boolean checkCorePermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_FINE_LOCATION_CODE);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (REQUEST_FINE_LOCATION_CODE == requestCode) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                showAlertDialog();
            } else {
                loading();
            }
        }
    }

    private void showAlertDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage(this.getString(R.string.permission_rationale, "定位"));
        dialog.setCancelable(false);
        dialog.setPositiveButton(getString(R.string.go_to_set), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //去往设置权限界面
                Utils.goToAppSettings(SplashActivity.this);//在此去往权限设置界面比重新申请要好，因为如果用户之前拒绝时选择了Never ask again再次申请也不会弹框
                finish();
            }
        });
        dialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
